import React, { useState, useEffect } from "react";
import axios from "axios";
import { Table, Space, Button, Tag, message } from "antd";

export default function Audit() {
  const [dataSource, setDataSource] = useState();
  const roleObj = {
    1: "superAdmin",
    2: "admin",
    3: "editor",
  };
  const { roleId, username, region } = JSON.parse(localStorage.getItem("user"));
  const fetchDate = async () => {
    const { data } = await axios.get("/news?&auditState=1&_expand=category");
    setDataSource(
      roleObj[roleId] === "superAdmin"
        ? data
        : [
            ...data.filter((item) => item.author === username),
            ...data.filter(
              (item) =>
                item.region === region && roleObj[item.roleId] === "editor"
            ),
          ]
    );
  };

  useEffect(() => {
    fetchDate();
  }, []);

  const handelCheck = async (id, auditState, publishState) => {
    const res = await axios.patch(`/news/${id}`, {
      auditState,
      publishState,
    });
    if (res.status === 200) {
      fetchDate();
      message.success("操作成功！");
    }
  };

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "新闻标题",
      dataIndex: "title",
      key: "title",
      render: (title, item) => (
        <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
      ),
    },
    {
      title: "作者",
      dataIndex: "author",
      key: "author",
    },
    {
      title: "分类",
      dataIndex: "category",
      key: "category",
      render: (category) => category.title,
    },
    {
      title: "审核状态",
      dataIndex: "auditState",
      key: "auditState",
      render: (auditState) => {
        const colorState = {
          0: "black",
          1: "orange",
          2: "green",
          4: "red",
        };
        const auditMap = {
          0: "未审核",
          1: "审核中",
          2: "已通过",
          3: "未通过",
        };
        return <Tag color={colorState[auditState]}>{auditMap[auditState]}</Tag>;
      },
    },
    {
      title: "操作",
      key: "action",
      render: (item) => (
        <Space size="middle">
          <Button
            type="primary"
            size="small"
            ghost
            onClick={() => handelCheck(item.id, 2, 1)}
          >
            通过
          </Button>
          <Button
            type="primary"
            size="small"
            danger
            ghost
            onClick={() => handelCheck(item.id, 3, 0)}
          >
            驳回
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Table
        bordered
        rowKey={(item) => item.id}
        dataSource={dataSource}
        columns={columns}
        pagination={{ pageSize: 10 }}
        size="small"
      />
    </div>
  );
}
